package com.cn.api.util;

import com.cn.api.error.ErrorCode;
import com.cn.api.error.ExceptionExpand;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUploadUtil {

	public static String upload(MultipartFile myfile, String realPath) throws IOException, ExceptionExpand {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String[] filename = myfile.getOriginalFilename().split("\\.");
		if (filename.length < 1) {
			throw new ExceptionExpand(ErrorCode.CODE_IMGTYPE_ERROR, ErrorCode.MESSAGE_IMGTYPE_ERROR);
		}
		String imgName = filename[0] + sdf.format(new Date()) + "." + filename[1];
		FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, imgName));
		return imgName;
	}

	public static String uploadVideo(MultipartFile myfile, String realPath) throws IOException, ExceptionExpand {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		if (myfile.getSize() > (Const.MAXVIDEO)) {
			throw new ExceptionExpand(ErrorCode.CODE_VIDEOSIZE_TOOMAX_ERROR, ErrorCode.MESSAGE_VIDEOSIZE_TOOMAX_ERROR);
		}
		String[] filename = myfile.getOriginalFilename().split("\\.");
		if (filename.length < 1) {
			throw new ExceptionExpand(ErrorCode.CODE_VIDEOTYPE_ERROR, ErrorCode.MESSAGE_VIDEOTYPE_ERROR);
		}
		String imgName = filename[0] + sdf.format(new Date()) + "." + filename[1];
		InputStream inputStream = myfile.getInputStream();
		FileUtils.copyInputStreamToFile(inputStream, new File(realPath, imgName));
		return imgName;
	}
}
